import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

// 用于标记是否已经添加过动态路由
let hasAddRoutes = false

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const hasToken = getToken()
  
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        if (!hasAddRoutes) {
          // 从localStorage获取菜单权限
          const menuStr = localStorage.getItem('menu_permissions')
          if (menuStr) {
            const menuPermissions = JSON.parse(menuStr)
            // 生成动态路由
            const accessRoutes = await store.dispatch('permission/generateRoutes', menuPermissions)
            // 添加动态路由
            accessRoutes.forEach(route => {
              router.addRoute(route)
            })
            hasAddRoutes = true
            // 重新进入当前路由，确保能够正确匹配新添加的路由
            next({ ...to, replace: true })
          } else {
            next('/login')
          }
        } else {
          next()
        }
      } catch (error) {
        console.error('路由处理错误:', error)
        Message.error(error.message || '路由处理出错')
        next('/login')
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
}) 